#include "tcpserver.h"
#include "ui_tcpserver.h"

TcpServer::TcpServer(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TcpServer)
{
    ui->setupUi(this);
    server = new QTcpServer();
    clientConnection = new QTcpSocket();
}

TcpServer::~TcpServer()
{
    delete ui;
}

void TcpServer::on_pushButton_clicked()
{
    server = new QTcpServer();
    clientConnection = new QTcpSocket();
    server->listen(QHostAddress::Any, 6666);
    connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
    ui->textBrowser->setText("开启监听");
}

void TcpServer::acceptConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
}

void TcpServer::readClient()
{
    qDebug("line31");
    QString str = clientConnection->readAll();
    ui->textBrowser->setText(str);
    if (str == "connected!")
    {
        clientConnection->write("Ready");
    }
}

void TcpServer::on_pushButton_2_clicked()
{
    server->close();
    clientConnection->abort();
    clientConnection->close();
}
